package com.hypo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hypo.mapper.NursingProjectPlanMapper;
import com.hypo.pojo.*;
import com.hypo.pojo.dto.NursingPlanDto;
import com.hypo.service.NursingPlanService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/nursingplan")
@RequiredArgsConstructor
public class NursingPlanController {
    private final NursingPlanService nursingPlanService;
    private final NursingProjectPlanMapper nursingProjectPlanMapper;

    /**
     * 分页查询
     *
     * @param nursingPlanQueryParam 请求数据
     * @return 返回
     */
    @GetMapping
    public Result pageQuery(NursingPlanQueryParam nursingPlanQueryParam) {
        //分页
        IPage<NursingPlan> page = new Page<>(nursingPlanQueryParam.getPage(), nursingPlanQueryParam.getPageSize());
        //条件查询
        LambdaQueryWrapper<NursingPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!Objects.isNull(nursingPlanQueryParam.getName()), NursingPlan::getPlanName, nursingPlanQueryParam.getName())
                .eq(!Objects.isNull(nursingPlanQueryParam.getStatus()), NursingPlan::getStatus, nursingPlanQueryParam.getStatus());

        IPage<NursingPlan> pageInfo = nursingPlanService.page(page, queryWrapper);
        return Result.success(new PageResult<>(pageInfo.getTotal(), pageInfo.getRecords()));
    }

    /**
     * 新增
     *
     * @param dto 请求数据
     * @return 返回
     */
    @Transactional
    @PostMapping
    public Result add(@RequestBody NursingPlanDto dto) {
        //新增护理计划
        NursingPlan nursingPlan = new NursingPlan();
        BeanUtils.copyProperties(dto, nursingPlan);
        nursingPlan.setCreateTime(LocalDateTime.now());
        nursingPlan.setUpdateTime(LocalDateTime.now());
        nursingPlanService.save(nursingPlan);
        //新增护理计划项目对象关系
        List<NursingProjectPlan> projectPlans = dto.getProjectList();
        //判断集合是否为空
        if (projectPlans != null && !projectPlans.isEmpty()) {
            for (NursingProjectPlan projectPlan : projectPlans) {
                //设置planId
                projectPlan.setPlanId(nursingPlan.getId());
                projectPlan.setCreateTime(LocalDateTime.now());
                projectPlan.setUpdateTime(LocalDateTime.now());
                nursingProjectPlanMapper.insert(projectPlan);
            }
        }
        return Result.success();
    }
}
